from django.shortcuts import render, HttpResponse
import torch
import os
import numpy as np
import scipy.io.wavfile as wavf


# Create your views here.

class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        y_pred = self.linear(x)
        return y_pred


file_base_dir = os.getcwd()

model = LinearModel()
model_path = os.getcwd() + '/nll/line.pkl'
model.load_state_dict(torch.load(model_path))
model.eval()
print('Model loaded successfully!')


def line(request):
    x = request.GET.get('x')
    pre_x_list = []
    pre_x_list.append(float(x))
    tx = torch.tensor(pre_x_list)
    with torch.no_grad():
        y = model(tx)

    return HttpResponse('y=' + str(y.item()))


def playwav(request):
    npy_dir = file_base_dir + '/nll/wavdata.npy'
    wav_file_name = '/nll/te.wav'

    wavdata_np = np.load(npy_dir)
    wavf.write(file_base_dir + wav_file_name, 24000, wavdata_np)

    return HttpResponse('successfully!')
